// pages/member_order/member_order.js
var common = require("../../../common/common.js").common;

const {$Toast: $Toast} = require("../../../components/base/index");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        nav: [ {
            id: 0,
            text: "全部"
        }, {
            id: 1,
            text: "待付款"
        }, {
            id: 2,
            text: "待发货"
        }, {
            id: 3,
            text: "配送中"
        }, {
            id: 4,
            text: "待取货"
        }, {
            id: 127,
            text: "已完成"
        }, {
            id: -126,
            text: "已售后"
        }, {
            id: -128,
            text: "已关闭"
        } ],
        choose_nav: 0,
        a: 2,
        page_sign: "member_order",
        order: [],
        search_con: "",
        clerk: [],
        isIPX: "",
        page: 1,
        //分页页码
        extract: 0,
        //配送方式
        goodsListStyle: {
            style: 4,
            styleConfig: {
                backgroundColor: "#fff"
            }
        },
        leader_receive: 0
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        var isIPX = app.globalData.isIPX;
        this.setData({
            isIPX: isIPX,
            domain: app.globalData.domain.slice(0, -10)
        });
        var that = this;
        that.setData({
            clerk: wx.getStorageSync("clerk")
        });
        this.getBase();
        this.getData();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        if (currentPage.__displayReporter.showReferpagepath == "pages/apply_refund/apply_refund.html") {
            //初始化页数，订单
            this.setData({
                page: 1,
                order: []
            });
            //从申请退款也返回，刷新数据
                        this.getData();
        }
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {
        this.getData();
    },
    /**
   * 用户点击右上角分享
   */
    choose_nav: function(e) {
        var that = this;
        var clerk = that.data.clerk;
        var openid = "";
        if (clerk.wom_status == 0) {
            openid = wx.getStorageSync("user").openid;
        } else {
            openid = clerk.leader_openid;
        }
        var id = e.currentTarget.dataset.id;
        var choose_nav = that.data.choose_nav;
        var extract = that.data.extract;
        if (id != choose_nav) {
            extract = 0;
            this.setData({
                choose_nav: id,
                page: 1,
                order: [],
                extract: extract
            });
            that.getData();
        }
    },
    makePhone: function(e) {
        var phone = e.currentTarget.dataset.phone;
        wx.makePhoneCall({
            phoneNumber: phone
        });
    },
    scancode: function() {
        var that = this;
        var clerk = that.data.clerk;
        var openid = "";
        if (clerk.wom_status == 0) {
            openid = wx.getStorageSync("user").openid;
        } else {
            openid = clerk.leader_openid;
        }
        wx.scanCode({
            success: res => {
                wx.navigateTo({
                    url: "/" + res.path,
                    success() {},
                    fail(err) {
                        wx.showModal({
                            title: "提示",
                            content: "请扫描正确的提货二维码"
                        });
                    }
                });
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: "请扫描正确的提货二维码",
                    showCancel: false
                });
            }
        });
    },
    getData: function() {
        var that = this;
        var clerk = that.data.clerk;
        var openid = "";
        var page = that.data.page;
        var extract = that.data.extract;
        var search_con = that.data.search_con;
        if (clerk.wom_status == 0) {
            openid = wx.getStorageSync("user").openid;
        } else {
            openid = clerk.leader_openid;
        }
        var id = that.data.choose_nav;
        common.request({
            endpoint: "Order/orderinfo/leaderorder2",
            method: "post",
            data: {
                openid: openid,
                status: id,
                page: page,
                delivery_channel: extract,
                search: search_con
            },
            success: res => {
                let data = that.data.order;
                //解构
                                var newData = that.orderList(res.extra);
                if (res.extra.length > 0) {
                    let order = page == 1 ? newData : data.concat(newData);
                    that.setData({
                        order: order
                    });
                    that.data.page = page + 1;
                }
            }
        });
    },
    getValue: function(e) {
        var that = this;
        var search_con = e.detail.value;
        that.setData({
            search_con: search_con
        });
    },
    search: function(e) {
        var that = this;
        that.setData({
            page: 1,
            order: []
        });
        that.getData();
    },
    confirm_pickUp: function(e) {
        var that = this;
        var result = e.currentTarget.dataset.result;
        var idx = e.currentTarget.dataset.idx;
        //确认收货订单的索引
                var order = that.data.order;
        //订单数组
                var choose_nav = that.data.choose_nav;
        //所选状态
                var clerk = that.data.clerk;
        var openid = "";
        if (clerk.wom_status == 0) {
            openid = wx.getStorageSync("user").openid;
        } else {
            openid = clerk.leader_openid;
        }
        wx.showModal({
            title: "提示",
            content: "请确认该团员已取货！！",
            success: function(res) {
                if (res.cancel) {} else {
                    common.request({
                        endpoint: "My/qrcode/change_status_bycode",
                        method: "post",
                        data: {
                            openid: openid,
                            result: result
                        },
                        header: {
                            "content-type": "application/json"
                        },
                        success: res => {
                            wx.showToast({
                                title: "取货成功",
                                icon: "success"
                            });
                            //全部订单状态时，确认取货后，改变该条订单状态为已完成
                            //待取货态时，确认取货后，改变该条订单状态为已完成
                                                        if (choose_nav == 0) {
                                //全部订单状态，改变订单状态
                                order[idx].status = 5;
                            } else {
                                //待取货状态，删除该条订单
                                order.splice(idx, 1);
                            }
                            that.setData({
                                order: order
                            });
                        },
                        fail: res => {
                            if (res.code == 4) {
                                wx.showToast({
                                    title: res.message,
                                    icon: "none"
                                });
                            } else {
                                wx.showToast({
                                    title: "取货失败",
                                    icon: "none"
                                });
                            }
                        }
                    });
                }
            },
            fail: function(res) {}
        });
    },
    share: function(e) {
        var trade_no = e.currentTarget.dataset.trade;
        wx.navigateTo({
            url: "/pages/order_confirm/order_confirm?order_no=" + trade_no
        });
    },
    extract: function(e) {
        var that = this;
        let extract = e.currentTarget.dataset.extract;
        that.setData({
            extract: extract,
            page: 1,
            order: []
        });
        that.getData();
    },
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                that.setData({
                    color_main: res.extra.color_main,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    leader_receive: res.extra.leader_receive
                });
            }
        });
    },
    orderList(data) {
        if (data || data.length > 0) {
            data.forEach((item, index) => {
                var newProArry = [];
                var deliveryCost = [];
                var aftermarket_num = 0;
                //可申请售后订单数量
                                var status3_num = 0;
                //待收货订单数量
                                var status4_num = 0;
                //待取货订单数量
                                var delivery1_num = 0;
                //自提订单数量
                                var delivery2_num = 0;
                //团长配送订单数量
                                var delivery3_num = 0;
                //平台配送订单数量
                // 拼运费字符串
                                if (item.esb_delivery && item.esb_delivery != "0.00") {
                    deliveryCost.push("平台配送费：￥" + item.esb_delivery);
                }
                if (item.express_delivery && item.express_delivery != "0.00") {
                    deliveryCost.push("快递配送费：￥" + item.express_delivery);
                }
                if (item.leader_delivery && item.leader_delivery != "0.00") {
                    deliveryCost.push("团长配送费：￥" + item.leader_delivery);
                }
                item.item.forEach((proInfo, proIndx) => {
                    if (proInfo.aftermarket_overtime == 1) {
                        aftermarket_num++;
                    }
                    if (proInfo.order_status == "4") {
                        status4_num++;
                    }
                    if (proInfo.order_status == "3") {
                        status3_num++;
                    }
                    switch (proInfo.delivery_channel) {
                      case "1":
                        delivery1_num++;
                        break;

                      case "2":
                        delivery2_num++;
                        break;

                      case "3":
                        delivery3_num++;
                        break;
                    }
                    var pro = {
                        id: proInfo.id,
                        //订单id，
                        proId: proInfo.pro_id,
                        //商品id
                        icon: proInfo.icon,
                        //商品缩略图
                        proName: proInfo.alias_name,
                        //商品名称
                        spec: proInfo.product_info,
                        //规格
                        money_refund: proInfo.money_refund,
                        //是否是满减商品
                        price: proInfo.price,
                        //商品单价
                        num: proInfo.num,
                        //数量
                        status: proInfo.status,
                        //售后状态，-1——仅退款，-2—— 退货退款，-3退货换货
                        order_status: proInfo.order_status,
                        //订单状态
                        isExpressPro: proInfo.delivery_channel == 4 ? 1 : 0,
                        //是否是快递商品，1是，2否
                        order_status: proInfo.order_status
                    };
                    newProArry.push(pro);
                });
                var newOrder = {
                    totalNum: item.allNum,
                    item: newProArry
                };
                item.goodsListData = newOrder;
                item.deliveryCost = "(" + (deliveryCost.length > 0 ? deliveryCost.join(",") : "免配送费") + ")";
                item.status4_num = status4_num;
                item.status3_num = status3_num;
                item.aftermarket_num = aftermarket_num;
                item.delivery1_num = delivery1_num;
                item.delivery2_num = delivery2_num;
                item.delivery3_num = delivery3_num;
            });
            return data;
        }
    },
    pageSwitch: function(e) {
        wx.showModal({
            title: "提示",
            content: "是否退出团长管理中心",
            success(res) {
                if (res.confirm) {
                    wx.switchTab({
                        url: e.currentTarget.dataset.url
                    });
                }
            }
        });
    },
    confirm_pickUp: function(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;
        let tradeNo = e.currentTarget.dataset.tradeno;
        let openid = wx.getStorageSync("user").openid;
        let mchid = e.currentTarget.dataset.mchid;
        let payment_channel = e.currentTarget.dataset.payment_channel;
        wx.showModal({
            title: "提示",
            content: "是否确认该团员已取货！",
            success: function(res) {
                if (res.cancel) {} else {
                    if (payment_channel == 2) {
                        if (wx.openBusinessView) {
                            wx.openBusinessView({
                                businessType: "weappOrderConfirm",
                                extraData: {
                                    merchant_id: mchid,
                                    merchant_trade_no: tradeNo,
                                    transaction_id: ""
                                },
                                success() {
                                    //dosomething
                                },
                                fail() {
                                    //dosomething
                                },
                                complete() {
                                    common.request({
                                        endpoint: "My/waitpick/change_status2",
                                        method: "post",
                                        data: {
                                            openid: openid,
                                            order_id: id
                                        },
                                        header: {
                                            "content-type": "application/json"
                                        },
                                        success: res => {
                                            wx.showToast({
                                                title: "取货成功",
                                                icon: "success"
                                            });
                                            let order = [];
                                            that.data.order.map(x => {
                                                if (x.trade_no != tradeNo) {
                                                    order.push(x);
                                                }
                                            });
                                            that.setData({
                                                order: order
                                            });
                                        },
                                        fail: res => {
                                            if (res.code == 4) {
                                                wx.showToast({
                                                    title: res.message,
                                                    icon: "none"
                                                });
                                            } else {
                                                wx.showToast({
                                                    title: "取货失败",
                                                    icon: "none"
                                                });
                                            }
                                        }
                                    });
                                    //dosomething
                                                                }
                            });
                        } else {
                            common.request({
                                endpoint: "My/waitpick/change_status2",
                                method: "post",
                                data: {
                                    openid: openid,
                                    order_id: id
                                },
                                header: {
                                    "content-type": "application/json"
                                },
                                success: res => {
                                    wx.showToast({
                                        title: "取货成功",
                                        icon: "success"
                                    });
                                    let order = [];
                                    that.data.order.map(x => {
                                        if (x.trade_no != tradeNo) {
                                            order.push(x);
                                        }
                                    });
                                    that.setData({
                                        order: order
                                    });
                                },
                                fail: res => {
                                    if (res.code == 4) {
                                        wx.showToast({
                                            title: res.message,
                                            icon: "none"
                                        });
                                    } else {
                                        wx.showToast({
                                            title: "取货失败",
                                            icon: "none"
                                        });
                                    }
                                }
                            });
                            //引导用户升级微信版本
                                                }
                    } else {
                        common.request({
                            endpoint: "My/waitpick/change_status2",
                            method: "post",
                            data: {
                                openid: openid,
                                order_id: id
                            },
                            header: {
                                "content-type": "application/json"
                            },
                            success: res => {
                                wx.showToast({
                                    title: "取货成功",
                                    icon: "success"
                                });
                                let order = [];
                                that.data.order.map(x => {
                                    if (x.trade_no != tradeNo) {
                                        order.push(x);
                                    }
                                });
                                that.setData({
                                    order: order
                                });
                            },
                            fail: res => {
                                if (res.code == 4) {
                                    wx.showToast({
                                        title: res.message,
                                        icon: "none"
                                    });
                                } else {
                                    wx.showToast({
                                        title: "取货失败",
                                        icon: "none"
                                    });
                                }
                            }
                        });
                    }
                }
            },
            fail: function(res) {}
        });
    },
    confirm_but: function(e) {
        let that = this;
        let item_ids = [];
        let item = e.currentTarget.dataset.info;
        let tradeNo = e.currentTarget.dataset.tradeno;
        item.map(x => {
            if (x.order_status == "3") {
                item_ids.push(x.id);
            }
        });
        wx.showModal({
            title: "提示",
            content: "是否确认收货！",
            success(res) {
                if (res.cancel) {} else {
                    common.request({
                        endpoint: "My/waitpick/leader_receive2",
                        method: "post",
                        data: {
                            item_ids: item_ids.join(","),
                            //item_ids
                            openid: wx.getStorageSync("user").openid
                        },
                        success: res => {
                            wx.showModal({
                                title: "提示",
                                content: "收货成功"
                            });
                            let order = [];
                            that.data.order.map(x => {
                                if (x.trade_no != tradeNo) {
                                    order.push(x);
                                }
                            });
                            that.setData({
                                order: order
                            });
                        },
                        fail(res) {
                            if (res.code == 2) {
                                $Toast({
                                    content: res.message
                                });
                            } else {
                                wx.showModal({
                                    title: "提示",
                                    content: "收货失败"
                                });
                            }
                        }
                    });
                }
            }
        });
    }
});